﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;

namespace Medianamik.UI.Controls
{
    public class Checkbox : BaseMedianamikControl
    {
        protected CheckBox chkCtrl;
        private MedianamikControlLabel _label;

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            chkCtrl = new CheckBox {ID = ControlToValidateId};
            Controls.Add(chkCtrl);

            _label = new CheckBoxLabel(chkCtrl);
            _label.IsLanguageNeutral = IsLanguageNeutral && !HideNeutralLanguageIndication;
            _label.Text = Label + " " + LabelExtensionText;

            Controls.Add(_label);

            if (pUseDataSource)
            {
                chkCtrl.CssClass = "CheckBox";
                chkCtrl.Checked = (bool?) DataSource ?? Checked;
                chkCtrl.TextAlign = TextAlign.Right;
            }
        }

        protected virtual bool Checked
        {
            get { return false; }
        }

        protected override bool SpecialLabel
        {
            get { return true; }
        }

        public override string ValidationExpression
        {
            get { return ""; }
            set { }
        }

        public override bool IsRequired
        {
            get { return false; }
            set { }
        }

        public override bool IsUnique
        {
            get { return false; }
            set { }
        }

        public override void SetValue(object value)
        {
            EnsureChildControls();
            if (value != null && value is bool)
                chkCtrl.Checked = (bool) value;
        }

        public override Type TypeOfValue
        {
            get { return typeof (bool); }
        }

        public override object GetValue()
        {
            EnsureChildControls();
            return chkCtrl.Checked;
        }

        private class CheckBoxLabel : MedianamikControlLabel
        {
            private readonly Control _forControl;

            public CheckBoxLabel(Control forControl)
            {
                _forControl = forControl;
            }

            protected override void AddAttributesToRender(HtmlTextWriter writer)
            {
                base.AddAttributesToRender(writer);
                writer.AddAttribute("for", _forControl.ClientID);
                writer.AddAttribute("style", "display:inline;font-weight:normal;margin-left:3px;");
            }
        }
    }
}